<template>
  <view class="questionnaire-preview-page">
    <!-- 导航栏 -->
    <view class="top">
      <s-nav-bar title="问卷预览" :background="'transparent'" :titleStyle="{ color: '#ffff', fontWeight: 'bold' }" statusBar
        immersive back :backStyle="{ color: '#fff' }" />

      <!-- 顶部区域 -->
      <view class="info">
        <view class="info-right">
          <view class="name">{{ questionnaire.title
          }}{{ questionnaire.is_template ? "[公共模板]" : "" }}</view>
        </view>
      </view>
    </view>

    <!-- 主内容区域 -->
    <scroll-view class="main" scroll-y="true">
      <view class="mainBox">
        <!-- 问卷基本信息 -->
        <view class="questionnaire-info">
          <view class="info-card">
            <view class="info-header">
              <view class="title">问卷信息</view>
            </view>

            <view class="info-content">
              <view class="info-item">
                <view class="label">状态</view>
                <view class="value">
                  <view class="status-tag" :class="questionnaire.status">
                    {{ statusText[questionnaire.status] || "未知" }}
                  </view>
                </view>
              </view>

              <view class="info-item">
                <view class="label">创建时间</view>
                <view class="value">{{
                  formatDate(questionnaire.created_at)
                }}</view>
              </view>

              <view class="info-item" v-if="questionnaire.answer_count > 0">
                <view class="label">收集数量</view>
                <view class="value">{{ questionnaire.answer_count }} 份</view>
              </view>
              <view class="info-item" @click="handleShare">
                <view class="value"><uni-easyinput v-model="shareUrl"></uni-easyinput></view>
              </view>
            </view>
          </view>
        </view>

        <!-- 问题列表 -->
        <view class="question-list">
          <view class="list-header">
            <view class="title">问题列表</view>
          </view>

          <view class="question-cards">
            <view class="question-card" v-for="(question, index) in questions" :key="getQuestionKey(question)">
              <view class="card-header">
                <view class="question-index">Q{{ index + 1 }}</view>
                <view class="question-type">[{{ getQuestionTypeText(question.type) }}]</view>
                <view class="question-title">{{ question.content }}</view>
                <view class="question-required" v-if="question.required">*</view>
              </view>

              <view class="card-content">
                <!-- 选择题选项预览 -->
                <view class="options-preview" v-if="['radio', 'check'].includes(question.type) &&
                  question.options
                  ">
                  <view class="option-item" v-for="(option, optIndex) in question.options" :key="optIndex">
                    <view class="option-label">{{ String.fromCharCode(65 + optIndex) }}.</view>
                    <view class="option-text">{{ option.label }}</view>
                  </view>
                </view>
              </view>
            </view>

            <view class="empty-tips" v-if="questions.length === 0">
              <s-icon name="box" size="40" color="#ccc" />
              <view class="empty-text">暂无问题</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer-actions">
      <s-button type="default" @click="handleShare"> 分享 </s-button>
      <s-button type="primary" @click="handleEdit" v-if="!questionnaire.is_template">
        编辑
      </s-button>
      <s-button type="primary" @click="createFromTemplate" v-else>
        从模板创建
      </s-button>
    </view>

    <!-- 创建问卷弹窗 -->
    <s-popup v-model="showCreatePopup" position="bottom" round :mask="true" mask-close>
      <view class="formContainer">
        <view class="formTitle">从模板创建问卷</view>

        <view class="formItem">
          <view class="formLabel">问卷标题</view>
          <uni-easyinput v-model="newQuestionnaireTitle" placeholder="请输入问卷标题" clearable />
        </view>

        <view class="buttonGroup">
          <s-button type="default" size="small" @click="showCreatePopup = false">
            取消
          </s-button>
          <s-button type="primary" size="small" @click="confirmCreateFromTemplate" :loading="loading">
            确认创建
          </s-button>
        </view>
      </view>
    </s-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      questionnaireId: null,
      shareUrl: '',
      questionnaire: {
        id: "",
        title: "",
        description: "",
        status: "draft",
        created_at: "",
        updated_at: "",
        answer_count: 0,
        is_template: false,
      },
      questions: [],

      // 状态文本
      statusText: {
        draft: "草稿",
        published: "已发布",
        closed: "已关闭",
      },

      // 问题类型选项
      questionTypes: [
        { value: "text", label: "填空题" },
        { value: "radio", label: "单选题" },
        { value: "check", label: "多选题" },
      ],

      // 从模板创建相关数据
      showCreatePopup: false,
      newQuestionnaireTitle: "",
      loading: false,
    };
  },
  onLoad(options) {
    this.questionnaireId = options.id;
    this.shareUrl = `https://survy.z550.com/?id=${this.questionnaireId}`;
    this.loadQuestionnaire();
  },
  methods: {
    // 加载问卷数据
    async loadQuestionnaire() {
      try {
        const res = await this.sjuAjax.get(
          `/questionnaire/detail?id=${this.questionnaireId}`
        );
        if (res && res.code === 200) {
          this.questionnaire = res.data.questionnaire || {
            id: "",
            title: "",
            description: "",
            status: "draft",
            created_at: "",
            updated_at: "",
            answer_count: 0,
            is_template: false,
          };

          // 设置默认标题
          this.newQuestionnaireTitle = this.questionnaire.title + "（副本）";

          // 处理问题数据
          this.questions = (res.data.questions || []).map((question) => {
            // 转换options格式
            let options = [];
            if (question.options && typeof question.options === "string") {
              try {
                const optionsObj = JSON.parse(question.options);
                options = Object.entries(optionsObj).map(([value, label]) => ({
                  value,
                  label,
                }));
              } catch (e) {
                console.error("解析选项失败:", e);
                options = [];
              }
            }

            return {
              ...question,
              options,
              required: question.is_required === "1",
            };
          });
        }
      } catch (error) {
        uni.showToast({
          title: "加载问卷失败",
          icon: "none",
        });
      }
    },
    handleShare() {


      // 复制到剪贴板
      uni.setClipboardData({
        data: this.shareUrl,
        success: () => {
          uni.showToast({
            title: "问卷地址已复制",
            icon: "success",
            duration: 2000,
          });
        },
        fail: () => {
          uni.showToast({
            title: "复制失败，请手动复制",
            icon: "none",
            duration: 2000,
          });
          // 如果复制失败，仍然显示链接让用户可以手动复制
          uni.showModal({
            title: "问卷链接",
            content: this.shareUrl,
            showCancel: false,
          });
        },
      });
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 获取问题类型文本
    getQuestionTypeText(type) {
      const typeMap = {
        text: "填空题",
        radio: "单选题",
        check: "多选题",
      };
      return typeMap[type] || type;
    },

    // 关闭预览
    handleClose() {
      uni.navigateBack();
    },

    // 编辑问卷
    handleEdit() {
      uni.navigateTo({
        url: `/pages/quest/edit?id=${this.questionnaireId}`,
      });
    },

    // 从模板创建问卷
    createFromTemplate() {
      this.showCreatePopup = true;
    },

    // 确认从模板创建问卷
    async confirmCreateFromTemplate() {
      if (!this.newQuestionnaireTitle) {
        uni.showToast({
          title: "请输入问卷标题",
          icon: "none",
        });
        return;
      }

      this.loading = true;
      try {
        const res = await this.sjuAjax.post("/questionnaire/copy", {
          id: this.questionnaireId,
          title: this.newQuestionnaireTitle,
        });

        if (res && res.code === 200) {
          uni.showToast({
            title: "创建成功",
            icon: "success",
          });

          // 跳转到编辑页面
          uni.navigateTo({
            url: `/pages/quest/edit?id=${res.data.id}`,
          });
        }
      } catch (error) {
        console.error("创建问卷失败:", error);
      } finally {
        this.loading = false;
      }
    },
    // 获取问题的唯一key值，解决非H5平台不支持表达式作为:key的问题
    getQuestionKey(question) {
      return question.id || question.tempId;
    },

    // 获取问题类型文本
    getQuestionTypeText(type) {
      const typeMap = {
        text: "填空(单行)",
        textarea: "填空(多行)",
        radio: "单选题",
        check: "多选题",
      };
      return typeMap[type] || type;
    },
  },
};
</script>

<style lang="scss">
.questionnaire-preview-page {
  width: 100vw;
  height: 100vh;
  background-color: var(--v-bg);
  display: flex;
  flex-direction: column;
}


/* 顶部区域 */
.top {
  width: 100vw;
  height: 320rpx;
  background: var(--v-linear);
  flex-shrink: 0;
  border-radius: 0 0 30rpx 30rpx;

  .info {
    display: flex;
    align-items: center;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;

    /* 右侧信息 */
    .info-right {
      display: flex;
      flex-direction: column;

      .name {
        margin-bottom: 10rpx;
      }

      .name {
        font-size: 44rpx;
        letter-spacing: 4rpx;
        color: #fff;
        text-shadow: 4rpx 4rpx 8rpx rgba(0, 0, 0, 0.4);
        line-height: 1.2;
      }

      .company {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.9);
        text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.3);
      }
    }
  }
}

/* 主内容区域 */
.main {
  position: relative;
  top: -50rpx;
  display: flex;
  flex-direction: column;
  height: 0;
  flex-grow: 1;
  padding-bottom: 100rpx;

  .mainBox {
    padding: 0 30rpx;
  }

  .questionnaire-info {
    margin-bottom: 20rpx;

    .info-card {
      background: rgba(255, 255, 255, 0.97);
      border-radius: 12rpx;
      padding: 24rpx;
      box-shadow: var(--v-shadow);

      .info-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
        padding-bottom: 10rpx;
        border-bottom: 1rpx solid #f5f5f5;

        .title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }
      }

      .info-content {
        .info-item {
          display: flex;
          margin-bottom: 16rpx;

          .label {
            width: 120rpx;
            font-size: 28rpx;
            color: #666;
          }

          .value {
            flex: 1;
            font-size: 28rpx;
            color: #333;

            .status-tag {
              display: inline-block;
              padding: 4rpx 12rpx;
              border-radius: 4rpx;
              font-size: 24rpx;

              &.draft {
                background-color: #f0f9eb;
                color: #67c23a;
              }

              &.published {
                background-color: #ecf5ff;
                color: #409eff;
              }

              &.closed {
                background-color: #fef0f0;
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
  }

  .question-list {
    background: rgba(255, 255, 255, 0.97);
    border-radius: 12rpx;
    padding: 24rpx;
    box-shadow: var(--v-shadow);

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }

    .question-cards {
      .question-card {
        background: #fff;
        border-radius: 8rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

        .card-header {
          display: flex;
          align-items: baseline;
          margin-bottom: 16rpx;
          padding-bottom: 30rpx;
          border-bottom: 1rpx solid #f5f5f5;
          gap: 14rpx;

          .question-index {
            font-weight: bold;
            color: var(--v-theme);
            flex-shrink: 0;
          }

          .question-type {
            font-size: 26rpx;
            color: #666;
            display: flex;
            align-items: center;
            flex-shrink: 0;
          }

          .question-required {
            font-size: 24rpx;
            color: #f56c6c;
          }

          .question-title {
            font-size: 30rpx;
            color: #333;
          }
        }

        .card-content {
          .options-preview {
            .option-item {
              display: flex;
              align-items: center;
              margin-bottom: 8rpx;

              .option-label {
                font-size: 24rpx;
                color: #999;
                margin-right: 8rpx;
              }

              .option-text {
                font-size: 26rpx;
                color: #666;
              }
            }
          }
        }
      }

      .empty-tips {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60rpx 0;
        color: #999;

        .empty-text {
          margin-top: 20rpx;
          font-size: 28rpx;
        }
      }
    }
  }
}

/* 底部操作栏 */
.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 20rpx;
  background: #fff;
  border-top: 1rpx solid #f5f5f5;

  >* {
    flex: 1;
    margin: 0 10rpx;
  }
}

/* 表单弹窗样式 */
.formContainer {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;

  .formTitle {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
    color: #333;
  }

  .formItem {
    margin-bottom: 30rpx;

    .formLabel {
      margin-bottom: 15rpx;
      font-size: 28rpx;
      color: #666;
    }
  }

  .buttonGroup {
    display: flex;
    justify-content: space-between;
    margin-top: 50rpx;

    button {
      flex: 1;
      margin: 0 10rpx;
    }
  }
}
</style>